<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>

<%
request.setCharacterEncoding("utf-8");

// 接收用户数据
String dish_id = request.getParameter("dish_id");
String name = request.getParameter("name");
String price = request.getParameter("price");
String amount = request.getParameter("amount");
String table_id = session.getAttribute("table_id").toString();
String restaurant_id = session.getAttribute("restaurant_id").toString();
String pay = "未支付";
String status = "waiting";
// 使用PreparedStatement避免SQL注入
String sql = "INSERT INTO cart (restaurant_id, dish_id, name, price, amount, table_id, status, pay) values('"+ restaurant_id +"','"+ dish_id +"','"+ name +"','"+ price +"','"+ amount +"','"+table_id +"','"+status +"','"+pay +"')";

try (Connection conn = DriverManager.getConnection("jdbc:mariadb://10.220.140.102:3366/studb14", "stu14", "jyw745DJ");
     PreparedStatement pstmt = conn.prepareStatement(sql)) {
    pstmt.setString(1, restaurant_id);
    pstmt.setString(2, dish_id);
    pstmt.setString(3, name);
    pstmt.setDouble(4, Double.parseDouble(price));
    pstmt.setInt(5, Integer.parseInt(amount));
    pstmt.setString(6, table_id);
    pstmt.setString(7, "waiting");
    pstmt.setString(8, "未支付");
    pstmt.setString(9, "0"); // admin_pwd

    int result = pstmt.executeUpdate();
    if (result > 0) {
        // 重定向到购物车详情页面
        response.sendRedirect("orderDetails.jsp");
    } else {
        // 处理添加失败的情况
    }
} catch (SQLException e) {
    // 异常处理
    e.printStackTrace();
}
%>